package server

import (
	"github.com/akirakazu/go-simplejson"
)

// "push" command handler
func (s *Server) onPush(id string, m *Pack) {
	identity := json.New()
	if !m.Msg.Has("from") {
		identity := s.conns[id].identity
		m.Msg.Set("from", identity)
	} else {
		identity = m.Msg.Get("from")
	}

	// Push message to all matched connections
	conns := s.findConns(m.Msg.Get("to"), identity)
	for _, c := range conns {
		s.send(c, m)
	}

	vias := []string{}
	vs, err := m.Msg.GetStringArray("__vias")
	if err == nil {
		vias = vs
	}
	proxies := s.allProxies(vias)

	if id == "" {
		vias = append(vias, s.proxy.id)
	} else {
		sessionId, err := identity.GetString("session_id")
		if err == nil {
			vias = append(vias, sessionId)
		}
	}
	m.Msg.Set("__vias", vias)

	for _, p := range proxies {
		s.send(p, m)
	}
	if s.proxy != nil && s.proxy.ready && !s.itemExists(s.proxy.id, vias) {
		s.proxy.sendPack(m)
	}
}
